import { isObject } from "@vue/shared";
import {
  mutableHandlers,
  shallowReactiveHandlers,
  readonlyHandlers,
  shallowReadonlyHandlers
} from './baseHandler';

const reactiveMap = new WeakMap();
const readonlyMap = new WeakMap();

/**
 * 
 * @param target 需要劫持的对象
 * @param isReadonly 是否只读
 * @param baseHandlers 
 * @returns 
 */
export function createReactiveObject(target, isReadonly, baseHandlers) {
  // 不是对象就返回
  if (!isObject(target)) {
    return target;
  }

  // 区分是否是只读
  const proxyMap = isReadonly ? readonlyMap : reactiveMap;
  
  const existProxy = proxyMap.get(target);
  // 如果对象已经代理了，就不再需要代理, 直接返回
  if (existProxy) {
    return existProxy;
  }
  const proxy = new Proxy(target, baseHandlers);
  proxyMap.set(target, proxy);

  return proxy;
}

export function reactive (target) {
  return createReactiveObject(target, false, mutableHandlers);
}
export function shallowReactive (target) {
  return createReactiveObject(target, false, shallowReactiveHandlers);
}
export function readonly (target) {
  return createReactiveObject(target, true, readonlyHandlers);
}
export function shallowReadonly (target) {
  return createReactiveObject(target, true, shallowReadonlyHandlers);
}